package edu.sdjzu.exam.service.redis;

import edu.sdjzu.exam.domain.examSession.Answer;
import edu.sdjzu.exam.domain.examSession.ExamSession;
import edu.sdjzu.exam.dto.examSession.SaveDraftDTO;
import edu.sdjzu.exam.mapper.examSession.AnswerMapper;
import edu.sdjzu.exam.mapper.examSession.ExamSessionMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Component
@RequiredArgsConstructor
public class DraftSyncTask {

    private final DraftRedisService draftRedisService;
    private final ExamSessionMapper examSessionMapper;
    private final AnswerMapper answerMapper;

    @Scheduled(fixedRate = 300000) // 每 5 分钟
    @Transactional
    public void syncDrafts() {
        List<ExamSession> sessions = examSessionMapper.selectExamSessionsByStatus("started", "interrupted");
        for (ExamSession session : sessions) {
            List<Answer> drafts = answerMapper.selectDraftsByExamAndStudent(session.getExamId(), session.getStudentId());
            for (Answer draft : drafts) {
                SaveDraftDTO draftDTO = draftRedisService.getDraftFromRedis(session.getSessionId(), draft.getQuestionId());
                if (draftDTO != null) {
                    draft.setAnswerContent(draftDTO.getAnswerContent());
                    draft.setFilePath(draftDTO.getFilePath());
                    draft.setAnswerTime(draftDTO.getAnswerTime());
                    answerMapper.updateAnswer(draft);
                }
            }
        }
    }
}
